package com.nil.codegen.utils;

import com.j256.simplemagic.ContentInfo;
import com.j256.simplemagic.ContentInfoUtil;
import com.nil.codegen.bean.FileStoreInfo;
import com.nil.codegen.config.minio.MinioProp;
import io.minio.MinioClient;
import io.minio.UploadObjectArgs;
import io.minio.errors.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.nio.file.Files;


@Slf4j
@Component
public class MinIOUtil {

    @Autowired
    private MinioClient client;

    @Autowired
    private MinioProp minioProp;

    /**
     *
     * @param file
     * @return
     */
    public FileStoreInfo uploadFile(MultipartFile file) {

        String localFileAbsolutePath = null;
        String minioPath = null;
        String extension = getExtension(file);
        String mimeType = getMimeType(extension);
        try {

            File localFile = File.createTempFile("minio", ".temp");
            file.transferTo(localFile);

            localFileAbsolutePath = localFile.getAbsolutePath();
            String folder = "temp/" + DateUtil.getUUID();
            String fileName = DigestUtils.md5Hex(Files.newInputStream(localFile.toPath()));
            minioPath = folder + fileName + extension;

            UploadObjectArgs uploadObjectArgs = UploadObjectArgs.builder()
                    .bucket(minioProp.getBucketName())
                    .filename(localFileAbsolutePath)
                    .object(minioPath)
                    .contentType(mimeType)
                    .build();

            client.uploadObject(uploadObjectArgs);
        } catch (Exception e) {
            log.error("文件上传失败！本地源文件路径：{}，minio目标文件路径：{}，错误信息：{}", localFileAbsolutePath, minioPath, e.getMessage());
        }

        FileStoreInfo fileStoreInfo = new FileStoreInfo();
        fileStoreInfo.setFileName(file.getOriginalFilename());
        fileStoreInfo.setUrl(minioProp.getEndpoint() + "/" + minioProp.getBucketName() + "/" + minioPath);
        fileStoreInfo.setExtension(extension);
        fileStoreInfo.setSize(file.getSize());

        log.info("文件上传成功: 访问路径: {}", fileStoreInfo.getUrl());
        return fileStoreInfo;
    }


    /**
     * 获取文件拓展名
     * @param file
     * @return
     */
    public static String getExtension(MultipartFile file) {
        String filename = file.getOriginalFilename();
        if (filename == null) {
            return "";
        }
        return filename.substring(filename.lastIndexOf("."));
    }


    /**
     *
     * @param extension 文件拓展名
     * @return mimeType
     */
    public static String getMimeType(String extension) {
        if (StringUtils.isEmpty(extension)) {
            return "";
        }

        String mimeType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        ContentInfo extensionMatch = ContentInfoUtil.findExtensionMatch(extension);
        if (extensionMatch != null){
            mimeType = extensionMatch.getMimeType();
        }
        return mimeType;
    }






}
